package com.dolphin.serviceorder.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dolphin.common.constant.CommonStatusEnum;
import com.dolphin.common.constant.DriverCarConstants;
import com.dolphin.common.constant.IdentityConstant;
import com.dolphin.common.constant.OrderConstants;
import com.dolphin.common.dto.*;
import com.dolphin.common.request.DriverGrabRequest;
import com.dolphin.common.request.OrderRequest;
import com.dolphin.common.request.PriceRuleIsNewRequest;
import com.dolphin.common.response.OrderDriverResponse;
import com.dolphin.common.response.TerminalResponse;
import com.dolphin.common.util.RedisPrefixUtils;
import com.dolphin.serviceorder.entity.DriverOrderStatistics;
import com.dolphin.serviceorder.mapper.DriverOrderStatisticsMapper;
import com.dolphin.serviceorder.mapper.OrderInfoMapper;
import com.dolphin.serviceorder.remote.ServiceDriverUserClient;
import com.dolphin.serviceorder.remote.ServiceMapClient;
import com.dolphin.serviceorder.remote.ServicePriceClient;
import com.dolphin.serviceorder.remote.ServiceSsePushClient;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author 小新
 * @since 2025-05-03
 */
@Service
@Slf4j
public class OrderInfoService {
    @Autowired
    OrderInfoMapper orderInfoMapper;
    @Autowired
    ServicePriceClient servicePriceClient;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    ServiceDriverUserClient serviceDriverUserClient;
    @Autowired
    ServiceMapClient serviceMapClient;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    ServiceSsePushClient serviceSsePushClient;
    @Autowired
    DriverOrderStatisticsMapper driverOrderStatisticsMapper;

    /**
     * 新建订单
     * @param orderRequest
     * @return
     */
    public ResponseResult add(OrderRequest orderRequest) {
        log.info("测试城市是否有司机结果");
        ResponseResult<Boolean> availableDriver = serviceDriverUserClient.isAvailableDriver(orderRequest.getAddress());
        if (!availableDriver.getData()) {
            return ResponseResult.fail(CommonStatusEnum.CITY_DRIVER_EMPTY.getCode(), CommonStatusEnum.CITY_DRIVER_EMPTY.getValue());
        }

        //需要判断计价规则的版本是否最新
        PriceRuleIsNewRequest   priceRuleIsNewRequest = new PriceRuleIsNewRequest();
        priceRuleIsNewRequest.setFareType(orderRequest.getFareType());
        priceRuleIsNewRequest.setFareVersion(orderRequest.getFareVersion());
        ResponseResult<Boolean> aNew = servicePriceClient.isNew(priceRuleIsNewRequest);
        if (!aNew.getData()) {
            return ResponseResult.fail(CommonStatusEnum.PRICE_RULE_CHANGED.getCode(), CommonStatusEnum.PRICE_RULE_CHANGED.getValue());

        }


        //需要判断 下单的设备号是否是 黑名单设备
        if (isBlackDevice(orderRequest))
            return ResponseResult.fail(CommonStatusEnum.DEVICE_IS_BLACK.getCode(), CommonStatusEnum.DEVICE_IS_BLACK.getValue());

        //判断：下单的城市是否提供服务
        if (!isPriceRuleExists(orderRequest)) {
            return ResponseResult.fail(CommonStatusEnum.CITY_SERVICE_NOT_SERVICE.getCode(), CommonStatusEnum.CITY_SERVICE_NOT_SERVICE.getValue());
        }

        //判断是否有业务中的订单
        if (isPassengerOrderGoingon(orderRequest.getPassengerId())>0) {
            return ResponseResult.fail(CommonStatusEnum.ORDER_GOING_ON.getCode(), CommonStatusEnum.ORDER_GOING_ON.getValue());
        }

        //创建订单
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(orderRequest, orderInfo);

        orderInfo.setOrderStatus(OrderConstants.ORDER_START);

        LocalDateTime now = LocalDateTime.now();
        orderInfo.setGmtCreate(now);
        orderInfo.setGmtModified(now);

        orderInfoMapper.insert(orderInfo);


        //定时任务的处理
        for (int i = 0; i < 6; i++) {
            // 派单 dispatchRealTimeOrder
            int result = dispatchRealTimeOrder(orderInfo);
            if (result == 1) {
                break;
            }
            if (i == 5) {
                //订单无效
                orderInfo.setOrderStatus(OrderConstants.ORDER_INVALID);
                orderInfoMapper.updateById(orderInfo);
            } else {
                try {
                    Thread.sleep(2);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }

        return ResponseResult.success();
    }

    public ResponseResult book(OrderRequest orderRequest) {
//        log.info("测试城市是否有司机结果");
//        ResponseResult<Boolean> availableDriver = serviceDriverUserClient.isAvailableDriver(orderRequest.getAddress());
//        if (!availableDriver.getData()) {
//            return ResponseResult.fail(CommonStatusEnum.CITY_DRIVER_EMPTY.getCode(), CommonStatusEnum.CITY_DRIVER_EMPTY.getValue());
//        }

        //需要判断计价规则的版本是否最新
//        PriceRuleIsNewRequest   priceRuleIsNewRequest = new PriceRuleIsNewRequest();
//        priceRuleIsNewRequest.setFareType(orderRequest.getFareType());
//        priceRuleIsNewRequest.setFareVersion(orderRequest.getFareVersion());
//        ResponseResult<Boolean> aNew = servicePriceClient.isNew(priceRuleIsNewRequest);
//        if (!aNew.getData()) {
//            return ResponseResult.fail(CommonStatusEnum.PRICE_RULE_CHANGED.getCode(), CommonStatusEnum.PRICE_RULE_CHANGED.getValue());
//
//        }


        //需要判断 下单的设备号是否是 黑名单设备
//        if (isBlackDevice(orderRequest))
//            return ResponseResult.fail(CommonStatusEnum.DEVICE_IS_BLACK.getCode(), CommonStatusEnum.DEVICE_IS_BLACK.getValue());

        //判断：下单的城市是否提供服务
//        if (!isPriceRuleExists(orderRequest)) {
//            return ResponseResult.fail(CommonStatusEnum.CITY_SERVICE_NOT_SERVICE.getCode(), CommonStatusEnum.CITY_SERVICE_NOT_SERVICE.getValue());
//        }

        //判断是否有业务中的订单
//        if (isPassengerOrderGoingon(orderRequest.getPassengerId())>0) {
//            return ResponseResult.fail(CommonStatusEnum.ORDER_GOING_ON.getCode(), CommonStatusEnum.ORDER_GOING_ON.getValue());
//        }

        //创建订单
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(orderRequest, orderInfo);

        orderInfo.setOrderStatus(OrderConstants.ORDER_START);

        LocalDateTime now = LocalDateTime.now();
        orderInfo.setGmtCreate(now);
        orderInfo.setGmtModified(now);

        orderInfoMapper.insert(orderInfo);


        //定时任务的处理
        for (int i = 0; i < 6; i++) {
            // 派单 dispatchRealTimeOrder
            int result = dispatchBookOrder(orderInfo);
            if (result == 1) {
                break;
            }
            if (i == 5) {
                //订单无效
                orderInfo.setOrderStatus(OrderConstants.ORDER_INVALID);
                orderInfoMapper.updateById(orderInfo);
            } else {
                try {
                    Thread.sleep(2);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }

        return ResponseResult.success();
    }

    /**
     * 实时订单派单逻辑
     * @param orderInfo
     * @return result  1:派单成功； 0：派单失败
     */
    public int dispatchRealTimeOrder(OrderInfo orderInfo) {
        log.info("循环一次");
        int result = 0;

        String depLongitude = orderInfo.getDepLongitude();
        String depLatitude = orderInfo.getDepLatitude();
        String center = depLatitude+"," + depLongitude;

        List<Integer> radiusList = Arrays.asList(2_000, 4_000, 5_000);
        ResponseResult<List<TerminalResponse>> listResponseResult ;

        radius:for (int i = 0; i < radiusList.size(); i++) {
            Integer radius = radiusList.get(i);
            listResponseResult = serviceMapClient.terminalAroundSearch(center, radius);

            log.info("寻找车辆，半径为：{},结果：{}", radius,JSONArray.fromObject(listResponseResult.getData()).toString());
            //获得终端 carId : 1918551017125838850   tId:1276607483


            //解析终端
            List<TerminalResponse> data = listResponseResult.getData();
//            为了测试是否从地图上获取到司机
//            List<TerminalResponse> data = new ArrayList<>();
            for (int j = 0; j < data.size(); j++) {
                TerminalResponse terminalResponse = data.get(j);
                Long carId = terminalResponse.getCarId();
                String latitude = terminalResponse.getLatitude();
                String longitude = terminalResponse.getLongitude();


                //查询是否有可用的可派单司机
                ResponseResult<OrderDriverResponse> availableDriver = serviceDriverUserClient.getAvailableDriver(carId);
                if (availableDriver.getCode() == CommonStatusEnum.AVAILABLE_DRIVER_EMPTY.getCode()) {
                    log.info("没有车辆ID:{},对应的司机",carId);
                    continue;
                } else {
                    log.info("找到司机：车辆id={},司机手机号：{}",availableDriver.getData().getCarId(),availableDriver.getData().getDriverPhone());
                    OrderDriverResponse orderDriverResponse = availableDriver.getData();
                    Long driverId = orderDriverResponse.getDriverId();
                    String driverPhone = orderDriverResponse.getDriverPhone();
                    String licenseId = orderDriverResponse.getLicenseId();
                    String vehicleNo = orderDriverResponse.getVehicleNo();
                    String vehicleTypeFromCar = orderDriverResponse.getVehicleType();

                    //判断车辆的车型是否符合
                    String vehicleType = orderInfo.getVehicleType();
                    if (vehicleType.trim().equals(vehicleTypeFromCar.trim())) {
                        log.info("车型不符合");
                        continue;
                    }

                    String lockKey = (driverId+"").intern();
                    RLock lock = redissonClient.getLock(lockKey);
                    lock.lock();
//                    判断司机 是否有进行中的订单
                    if (isDriverOrderGoingon(driverId) > 0) {
                        log.info("司机：手机号={},司机ID={},有进行中的订单", availableDriver.getData().getDriverPhone(), availableDriver.getData().getDriverId());
                        lock.unlock();
                        continue;
                    }

                    //订单直接匹配
                    orderInfo.setDriverId(driverId);
                    orderInfo.setDriverPhone(driverPhone);
                    orderInfo.setCarId(carId);
                    orderInfo.setReceiveOrderCarLongitude(longitude);
                    orderInfo.setReceiveOrderCarLatitude(latitude);
                    orderInfo.setReceiveOrderTime(LocalDateTime.now());
                    orderInfo.setLicenseId(licenseId);
                    orderInfo.setVehicleNo(vehicleNo);
                    orderInfo.setOrderStatus(OrderConstants.DRIVER_RECEIVE_ORDER);

                    orderInfoMapper.updateById(orderInfo);

                    //通知司机
                    JSONObject driverContent = new JSONObject();
                    driverContent.put("orderId", orderInfo.getId());
                    driverContent.put("passengerId", orderInfo.getPassengerId());
                    driverContent.put("passengerPhone", orderInfo.getPassengerPhone());
                    driverContent.put("departure", orderInfo.getDeparture());
                    driverContent.put("depLongitude", orderInfo.getDepLongitude());
                    driverContent.put("depLatitude", orderInfo.getDepLatitude());

                    driverContent.put("destination", orderInfo.getDestination());
                    driverContent.put("destLongitude", orderInfo.getDestLongitude());
                    driverContent.put("destLatitude", orderInfo.getDestLatitude());

                    serviceSsePushClient.push(driverId, IdentityConstant.DRIVER_IDENTITY, driverContent.toString());


                    //通知乘客
                    JSONObject passengerContent = new JSONObject();
                    passengerContent.put("orderId", orderInfo.getId());
                    passengerContent.put("driverId", orderInfo.getDriverId());
                    passengerContent.put("driverPhone", orderInfo.getDriverPhone());
                    passengerContent.put("vehicleNo", orderInfo.getVehicleNo());
                    //车辆信息,调用车辆服务
                    ResponseResult<Car> carById = serviceDriverUserClient.getCarById(orderInfo.getCarId());
                    Car carRemote = carById.getData();

                    passengerContent.put("brand",  carRemote.getBrand());
                    passengerContent.put("model",  carRemote.getModel());
                    passengerContent.put("vehicleColor",  carRemote.getVehicleColor());


                    passengerContent.put("receiveOrderCarLongitude", orderInfo.getReceiveOrderCarLongitude());
                    passengerContent.put("receiveOrderCarLatitude", orderInfo.getReceiveOrderCarLatitude());

                    serviceSsePushClient.push(orderInfo.getPassengerId(), IdentityConstant.PASSENGER_IDENTITY, passengerContent.toString());

                    result = 1;

                    lock.unlock();
                    //退出，不再进行司机的查找
                    break radius;
                }
            }
        }
        return result;
    }

    /**
     * 预约订单-分发订单
     * @param orderInfo
     * @return
     */
    public int dispatchBookOrder(OrderInfo orderInfo) {
        log.info("循环一次");
        int result = 0;

        String depLongitude = orderInfo.getDepLongitude();
        String depLatitude = orderInfo.getDepLatitude();
        String center = depLatitude+"," + depLongitude;

        List<Integer> radiusList = Arrays.asList(2_000, 4_000, 5_000);
        ResponseResult<List<TerminalResponse>> listResponseResult ;

        radius:for (int i = 0; i < radiusList.size(); i++) {
            Integer radius = radiusList.get(i);
            listResponseResult = serviceMapClient.terminalAroundSearch(center, radius);

            log.info("寻找车辆，半径为：{},结果：{}", radius,JSONArray.fromObject(listResponseResult.getData()).toString());
            //获得终端 carId : 1918551017125838850   tId:1276607483


            //解析终端
//            List<TerminalResponse> data = listResponseResult.getData();
//            为了测试是否从地图上获取到司机
            List<TerminalResponse> data = new ArrayList<>();
            TerminalResponse testTerminal = new TerminalResponse();
            testTerminal.setCarId(6L);
            testTerminal.setTid("1281984326");
            testTerminal.setLatitude("36.88");
            testTerminal.setLongitude("112.98");
            data.add(testTerminal);



            for (int j = 0; j < data.size(); j++) {
                TerminalResponse terminalResponse = data.get(j);
                Long carId = terminalResponse.getCarId();
                String latitude = terminalResponse.getLatitude();
                String longitude = terminalResponse.getLongitude();


                //查询是否有可用的可派单司机
                ResponseResult<OrderDriverResponse> availableDriver = serviceDriverUserClient.getAvailableDriver(carId);
                if (availableDriver.getCode() == CommonStatusEnum.AVAILABLE_DRIVER_EMPTY.getCode()) {
                    log.info("没有车辆ID:{},对应的司机",carId);
                    continue;
                } else {
                    log.info("找到司机：车辆id={},司机手机号：{}",availableDriver.getData().getCarId(),availableDriver.getData().getDriverPhone());
                    OrderDriverResponse orderDriverResponse = availableDriver.getData();
                    Long driverId = orderDriverResponse.getDriverId();
                    String driverPhone = orderDriverResponse.getDriverPhone();
                    String licenseId = orderDriverResponse.getLicenseId();
                    String vehicleNo = orderDriverResponse.getVehicleNo();
                    String vehicleTypeFromCar = orderDriverResponse.getVehicleType();

                    //判断车辆的车型是否符合
                    String vehicleType = orderInfo.getVehicleType();
                    if (vehicleType.trim().equals(vehicleTypeFromCar.trim())) {
                        log.info("车型不符合");
                        continue;
                    }



                    //通知司机
                    JSONObject driverContent = new JSONObject();
                    driverContent.put("orderId", orderInfo.getId());
                    driverContent.put("passengerId", orderInfo.getPassengerId());
                    driverContent.put("passengerPhone", orderInfo.getPassengerPhone());
                    driverContent.put("departure", orderInfo.getDeparture());
                    driverContent.put("depLongitude", orderInfo.getDepLongitude());
                    driverContent.put("depLatitude", orderInfo.getDepLatitude());

                    driverContent.put("destination", orderInfo.getDestination());
                    driverContent.put("destLongitude", orderInfo.getDestLongitude());
                    driverContent.put("destLatitude", orderInfo.getDestLatitude());

                    serviceSsePushClient.push(driverId, IdentityConstant.DRIVER_IDENTITY, driverContent.toString());
                    result =1;
                    //退出，不再进行司机的查找
                    break radius;
                }
            }
        }
        return result;
    }


    /**
     * 计价规则是否存在
     * @param orderRequest
     * @return
     */
    private boolean isPriceRuleExists(OrderRequest orderRequest) {
        String fareType = orderRequest.getFareType();
        int index = fareType.indexOf("$");
        String cityCode = fareType.substring(0, index);
        String vehicleType = fareType.substring(index + 1);

        PriceRule priceRule = new PriceRule();
        priceRule.setCityCode(cityCode);
        priceRule.setVehicleType(vehicleType);
        return servicePriceClient.ifExists(priceRule).getData();
    }

    /**
     * 是否是黑名单
     * @param orderRequest
     * @return
     */
    private boolean isBlackDevice(OrderRequest orderRequest) {
        String deviceCode = orderRequest.getDeviceCode();
        //生成key
        String deviceCodeKey = RedisPrefixUtils.blackDevicePrefix + deviceCode;
        //判断设备是否超过下单次数
        //设置key,看原来有没有key
        //判断当前设备下单次数是否超过指定次数  这里是2，超过不允许下单，1小时内只能下2单
        Boolean hasKey = stringRedisTemplate.hasKey(deviceCodeKey);
        if (hasKey) {
            String s = stringRedisTemplate.opsForValue().get(deviceCodeKey);
            int i = Integer.parseInt(s);
            if (i >= 2) {
                return true;
            } else {
                stringRedisTemplate.opsForValue().increment(deviceCodeKey);
            }

        } else {
            stringRedisTemplate.opsForValue().setIfAbsent(deviceCodeKey, "1", 1, TimeUnit.HOURS);
        }
        return false;
    }

    /**
     * 判断乘客是否有业务中的订单
     * @param passengerId
     * @return
     */
    private int isPassengerOrderGoingon(Long passengerId) {
        //判断有正在进行的订单
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getPassengerId, passengerId)
                .in(OrderInfo::getOrderStatus,
                        OrderConstants.ORDER_START,
                        OrderConstants.DRIVER_RECEIVE_ORDER,
                        OrderConstants.DRIVER_TO_PICK_UP_PASSENGER,
                        OrderConstants.DRIVER_ARRIVED_DEPARTURE,
                        OrderConstants.PICK_UP_PASSENGER,
                        OrderConstants.PASSENGER_GET_OFF,
                        OrderConstants.TO_START_PAY

                );
        Integer validOrderNumber = orderInfoMapper.selectCount(queryWrapper);
        return validOrderNumber;

    }

    /**
     * 判断司机是否有业务中的订单
     * @param driverId
     * @return
     */
    private int isDriverOrderGoingon(Long driverId) {
        //判断有正在进行的订单
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getDriverId, driverId)
                .in(OrderInfo::getOrderStatus,
                        OrderConstants.DRIVER_RECEIVE_ORDER,
                        OrderConstants.DRIVER_TO_PICK_UP_PASSENGER,
                        OrderConstants.DRIVER_ARRIVED_DEPARTURE,
                        OrderConstants.PICK_UP_PASSENGER
                );
        Integer validOrderNumber = orderInfoMapper.selectCount(queryWrapper);
        log.info("司机ID={},正在进行的订单数量={}",driverId,validOrderNumber);
        return validOrderNumber;

    }


    /**
     * 去接乘客
     * @param orderRequest
     * @return
     */
    public ResponseResult toPickUpPassenger(OrderRequest orderRequest) {
        Long orderId = orderRequest.getOrderId();
        LocalDateTime toPickUpPassengerTime = orderRequest.getToPickUpPassengerTime();
        String toPickUpPassengerLongitude = orderRequest.getToPickUpPassengerLongitude();
        String toPickUpPassengerLatitude = orderRequest.getToPickUpPassengerLatitude();
        String toPickUpPassengerAddress = orderRequest.getToPickUpPassengerAddress();

        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderInfo::getId,  orderId);
        OrderInfo orderInfo = orderInfoMapper.selectOne(lambdaQueryWrapper);

        orderInfo.setToPickUpPassengerTime(LocalDateTime.now());
        orderInfo.setToPickUpPassengerLongitude(toPickUpPassengerLongitude);
        orderInfo.setToPickUpPassengerLatitude(toPickUpPassengerLatitude);
        orderInfo.setToPickUpPassengerAddress(toPickUpPassengerAddress);
        orderInfo.setOrderStatus(OrderConstants.DRIVER_TO_PICK_UP_PASSENGER);

        orderInfoMapper.updateById(orderInfo);

        return ResponseResult.success();


    }

    /**
     * 司机到达乘客上车点
     * @param orderRequest
     * @return
     */
    public ResponseResult arriveDeparture(OrderRequest orderRequest) {
        Long orderId = orderRequest.getOrderId();

        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderInfo::getId,  orderId);
        OrderInfo orderInfo = orderInfoMapper.selectOne(lambdaQueryWrapper);
        orderInfo.setDriverArrivedDepartureTime(LocalDateTime.now());
        orderInfo.setOrderStatus(OrderConstants.DRIVER_ARRIVED_DEPARTURE);
        orderInfoMapper.updateById(orderInfo);
        return ResponseResult.success();
    }

    /**
     * 乘客上车
     * @param orderRequest
     * @return
     */
    public ResponseResult pickUpPassenger(OrderRequest orderRequest) {
        Long orderId = orderRequest.getOrderId();

        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderInfo::getId,  orderId);
        OrderInfo orderInfo = orderInfoMapper.selectOne(lambdaQueryWrapper);

        orderInfo.setPickUpPassengerTime(LocalDateTime.now());
        orderInfo.setPickUpPassengerLongitude(orderRequest.getPickUpPassengerLongitude());
        orderInfo.setPickUpPassengerLatitude(orderRequest.getPickUpPassengerLatitude());
        orderInfo.setOrderStatus(OrderConstants.PICK_UP_PASSENGER);
        orderInfoMapper.updateById(orderInfo);
        return ResponseResult.success();


    }

    /**
     * 乘客下车
     * @param orderRequest
     * @return
     */
    public ResponseResult passengerGetOff(OrderRequest orderRequest) {

        Long orderId = orderRequest.getOrderId();
        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderInfo::getId,  orderId);
        OrderInfo orderInfo = orderInfoMapper.selectOne(lambdaQueryWrapper);


        orderInfo.setPassengerGetoffTime(LocalDateTime.now());
        orderInfo.setPassengerGetoffLongitude(orderRequest.getPassengerGetoffLongitude());
        orderInfo.setPassengerGetoffLatitude(orderRequest.getPassengerGetoffLatitude());
        orderInfo.setOrderStatus(OrderConstants.PASSENGER_GET_OFF);


        ResponseResult<Car> carById = serviceDriverUserClient.getCarById(orderInfo.getCarId());

        //订单行驶的路程和时间
        long starttime = orderInfo.getPickUpPassengerTime().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long enttime = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        ResponseResult<TrsearchResponse> trsearch = serviceMapClient.trsearch(carById.getData().getTid(),
                starttime,enttime);
        TrsearchResponse data = trsearch.getData();
        Long driverMile = data.getDriverMile();
        Long driverTime = data.getDriverTime();
        orderInfo.setDriveMile(driverMile);
        orderInfo.setDriveTime(driverTime);

        //获取价格
        String address = orderInfo.getAddress();
        String vehicleType = orderInfo.getVehicleType();
        ResponseResult<Double> result = servicePriceClient.calculatePrice(
                driverMile.intValue(),
                driverTime.intValue(),
                address,
                vehicleType);
        Double price = result.getData();
        orderInfo.setPrice(price);
        orderInfoMapper.updateById(orderInfo);

        return ResponseResult.success();

    }

    public ResponseResult pay(OrderRequest orderRequest) {
        Long orderId = orderRequest.getOrderId();
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        orderInfo.setOrderStatus(OrderConstants.SUCCESS_PAY);
        orderInfoMapper.updateById(orderInfo);
        return ResponseResult.success();
    }

    public ResponseResult cancel(Long orderId, String identity) {
        //查询订单当前状态
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        Integer orderStatus = orderInfo.getOrderStatus();

        LocalDateTime cancelTime = null;
        Integer cancelOperator = null;
        Integer cancelTypeCode = null;


        //更新订单取消状态
        //如果是乘客取消
        int cancelType = 1;
        if (identity.trim().equals(IdentityConstant.PASSENGER_IDENTITY)) {
            cancelOperator = Integer.valueOf(IdentityConstant.PASSENGER_IDENTITY);
            switch (orderStatus) {
                //订单开始—— 乘客提前取消
                case  OrderConstants.ORDER_START:
                    cancelTypeCode = OrderConstants.CANCEL_PASSENGER_BEFORE;
                    break;
                //司机接单   1分钟内：乘客提前取消  超过1分钟：乘客违约取消
                case OrderConstants.DRIVER_RECEIVE_ORDER:
                    LocalDateTime receiveOrderTime = orderInfo.getReceiveOrderTime();
                    long between = ChronoUnit.MINUTES.between(receiveOrderTime, LocalDateTime.now());
                    if (between > 1) {
                        cancelTypeCode = OrderConstants.CANCEL_PASSENGER_ILLEGAL;
                    } else {
                        cancelTypeCode = OrderConstants.CANCEL_PASSENGER_BEFORE;
                    }
                    break;
                //司机去接乘客
                case OrderConstants.DRIVER_TO_PICK_UP_PASSENGER:
                    cancelTypeCode = OrderConstants.CANCEL_PASSENGER_ILLEGAL;
                    break;
                //司机到达乘客接乘客地
                case OrderConstants.DRIVER_ARRIVED_DEPARTURE:
                    cancelTypeCode = OrderConstants.CANCEL_PASSENGER_ILLEGAL;
                    break;
                default:

                    log.info("乘客取消失败");
                    cancelType = 0;
                    break;

            }
        }


        //如果是司机取消
        if (identity.trim().equals(IdentityConstant.DRIVER_IDENTITY)) {
            cancelOperator = Integer.valueOf(IdentityConstant.DRIVER_IDENTITY);
            switch (orderStatus) {
                //订单开始—— 乘客提前取消
                //司机接单   1分钟内：司机提前取消  超过1分钟：司机违约取消
                case OrderConstants.DRIVER_RECEIVE_ORDER:
                //司机去接乘客
                case OrderConstants.DRIVER_TO_PICK_UP_PASSENGER:
                    //司机到达乘客接乘客地
                case OrderConstants.DRIVER_ARRIVED_DEPARTURE:
                    LocalDateTime receiveOrderTime = orderInfo.getReceiveOrderTime();
                    long between = ChronoUnit.MINUTES.between(receiveOrderTime, LocalDateTime.now());
                    if (between > 1) {
                        cancelTypeCode = OrderConstants.CANCEL_DRIVER_ILLEGAL;
                    } else {
                        cancelTypeCode = OrderConstants.CANCEL_DRIVER_BEFORE;
                    }
                    break;
                default:

                    log.info("司机取消失败");
                    cancelType = 0;
                    break;

            }
        }


        if (cancelType == 0) {
            return ResponseResult.fail(CommonStatusEnum.ORDER_CANCEL_ERROR.getCode(),CommonStatusEnum.ORDER_CANCEL_ERROR.getValue());
        }


        orderInfo.setCancelOperator(Integer.parseInt(identity));
        orderInfo.setCancelTime(cancelTime);
        orderInfo.setCancelTypeCode(cancelTypeCode);
        orderInfo.setCancelOperator(cancelOperator);
        orderInfo.setOrderStatus(OrderConstants.ORDER_CANCEL);


        orderInfoMapper.updateById(orderInfo);

        return ResponseResult.success();
    }

    public ResponseResult pushPayInfo(OrderRequest orderRequest) {
        Long orderId = orderRequest.getOrderId();
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        orderInfo.setOrderStatus(OrderConstants.TO_START_PAY);
        orderInfoMapper.updateById(orderInfo);
        return ResponseResult.success();
    }

    public ResponseResult<OrderInfo> detail(Long orderId){
        OrderInfo orderInfo =  orderInfoMapper.selectById(orderId);
        return ResponseResult.success(orderInfo);
    }
    public ResponseResult<OrderInfo> current(String phone, String identity){
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();

        if (identity.equals(IdentityConstant.DRIVER_IDENTITY)){
            queryWrapper.eq("driver_phone",phone);

            queryWrapper.and(wrapper->wrapper
                    .eq("order_status",OrderConstants.DRIVER_RECEIVE_ORDER)
                    .or().eq("order_status",OrderConstants.DRIVER_TO_PICK_UP_PASSENGER)
                    .or().eq("order_status",OrderConstants.DRIVER_ARRIVED_DEPARTURE)
                    .or().eq("order_status",OrderConstants.PICK_UP_PASSENGER)

            );
        }
        if (identity.equals(IdentityConstant.PASSENGER_IDENTITY)){
            queryWrapper.eq("passenger_phone",phone);
            queryWrapper.and(wrapper->wrapper.eq("order_status",OrderConstants.ORDER_START)
                    .or().eq("order_status",OrderConstants.DRIVER_RECEIVE_ORDER)
                    .or().eq("order_status",OrderConstants.DRIVER_TO_PICK_UP_PASSENGER)
                    .or().eq("order_status",OrderConstants.DRIVER_ARRIVED_DEPARTURE)
                    .or().eq("order_status",OrderConstants.PICK_UP_PASSENGER)
                    .or().eq("order_status",OrderConstants.PASSENGER_GET_OFF)
                    .or().eq("order_status",OrderConstants.TO_START_PAY)
            );
        }

        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        return ResponseResult.success(orderInfo);
    }

    /**
     * 司机抢单
     * @param driverGrabRequest
     * @return
     */
    public ResponseResult<OrderInfo> grab(DriverGrabRequest driverGrabRequest) {
        Long orderId = driverGrabRequest.getOrderId();
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (orderInfo == null) {
            return ResponseResult.fail(CommonStatusEnum.ORDER_NOT_EXISTS.getCode(),CommonStatusEnum.ORDER_NOT_EXISTS.getValue());
        }
        int orderStatus = orderInfo.getOrderStatus();
        if (orderStatus != OrderConstants.ORDER_START) {
            return ResponseResult.fail(CommonStatusEnum.ORDER_CAN_NOT_GRAB.getCode(),CommonStatusEnum.ORDER_CAN_NOT_GRAB.getValue());
        }


        Long driverId = driverGrabRequest.getDriverId();
        Long carId = driverGrabRequest.getCarId();
        String licenseId = driverGrabRequest.getLicenseId();
        String vehicleNo = driverGrabRequest.getVehicleNo();
        String vehicleType = driverGrabRequest.getVehicleType();
        String receiveOrderCarLongitude = driverGrabRequest.getReceiveOrderCarLongitude();
        String receiveOrderCarLatitude = driverGrabRequest.getReceiveOrderCarLatitude();
        String driverPhone = driverGrabRequest.getDriverPhone();

        orderInfo.setDriverId(driverId);
        orderInfo.setCarId(carId);
        orderInfo.setLicenseId(licenseId);
        orderInfo.setVehicleNo(vehicleNo);
        orderInfo.setVehicleType(vehicleType);
        orderInfo.setReceiveOrderCarLongitude(receiveOrderCarLongitude);
        orderInfo.setReceiveOrderCarLatitude(receiveOrderCarLatitude);
        orderInfo.setDriverPhone(driverPhone);

        orderInfo.setOrderStatus(OrderConstants.DRIVER_RECEIVE_ORDER);

        orderInfoMapper.updateById(orderInfo);

        //添加司机当前抢单成功的数量
        //先查询当前的数据
        LambdaQueryWrapper<DriverOrderStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DriverOrderStatistics::getGrabOrderDate, LocalDate.now());
        queryWrapper.eq(DriverOrderStatistics::getDriverId, driverId);
        DriverOrderStatistics driverOrderStatistics = driverOrderStatisticsMapper.selectOne(queryWrapper);

        if (driverOrderStatistics == null) {
            driverOrderStatistics = new DriverOrderStatistics();
            driverOrderStatistics.setGrabOrderDate(LocalDate.now());
            driverOrderStatistics.setGrabOrderSuccessCount(1);
            driverOrderStatistics.setDriverId(driverId);
            driverOrderStatisticsMapper.insert(driverOrderStatistics);

        } else {
            driverOrderStatistics.setGrabOrderSuccessCount(driverOrderStatistics.getGrabOrderSuccessCount() + 1);
            driverOrderStatisticsMapper.updateById(driverOrderStatistics);
        }


        return ResponseResult.success();
    }
}


